<template>
  <!-- 简单导航 -->
  <SimpleNav/>
  <section class="login-form">
    <!-- 定义一个容器、水平垂直居中 -->
    <main class="login-container">
      <div class="login-bg"></div>
      <div class="login-core">
        <div class="login-tab" @click="swtichTab">
          <span data-name="0" :class="{active: switchType}">用户登录</span>
          <span data-name="1" :class="{active: !switchType}">用户注册</span>
        </div>
        <!-- 显示登录组件 -->
        <div class="login-panel">
            <el-form :model="login" v-show="switchType" style="width: 100%">
              <el-form-item>
                <el-input v-model="login.username" size="large" placeholder="请输入邮箱账号">
                  <template #suffix>
                    <el-icon :size="26">
                      <Message/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-input v-model="login.password" type="password" size="large" placeholder="请输入密码">
                  <template #suffix>
                    <el-icon :size="26">
                      <Unlock/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="login.rememberMe" size="large">30天自动登录</el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="large" style="width: 100%;" @click.prevent="onSubmitLogin">登录</el-button>
              </el-form-item>
              <a class="login-fda" @click="findPass">忘记密码，点我找回</a>
            </el-form>

            <el-form :model="form" v-show="!switchType"  style="width: 100%">

              <el-form-item>
                <el-input v-model="form.email" size="large" placeholder="请输入邮箱账号">
                  <template #suffix>
                    <el-icon :size="26">
                      <Message/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-input v-model="form.password" type="password" size="large" placeholder="请输入密码">
                  <template #suffix>
                    <el-icon :size="26">
                      <Unlock/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-input v-model="form.password2" type="password" size="large" placeholder="请再次输入密码">
                  <template #suffix>
                    <el-icon :size="26">
                      <Unlock/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-select v-model="form.clazz_id" size="large" clearable placeholder="请选择班级">
                  <el-option v-for="item in clazzList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>


              <el-form-item>
                <el-input v-model="form.name" size="large" placeholder="请输入真实姓名">
                  <template #suffix>
                    <el-icon :size="26">
                      <User/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

            
              <el-form-item>
                <el-button type="primary" size="large" style="width: 100%;" @click.prevent="onSubmitRegister">注册</el-button>
              </el-form-item>
            </el-form>
        </div>

      </div>
    </main>
  </section>
</template>
<script>
import router from '@/router';
import SimpleNav from '@/components/SimpleNav.vue'
import API from '@/api/index.js';
import Token from '@/api/token.js';

export default {
  data() {
    return {
      switchType: true, // 控制登录或注册
      login: {
        username: '',
        password: '',
        rememberMe: true,
      },
      form: {
        email: "",
        password: "",
        password2: "",
        name: "",
        clazz_id: null,
      },
      clazzList: [],
    };
  },

  created() {
    API.clazz_list().then(res => {
      this.clazzList = res;
    })
  },

  methods: {
    swtichTab(event) {
      if (event.target.nodeName === "SPAN") {
        this.switchType = event.target.dataset.name !== "1";
      }
    },
    
    onSubmitLogin() {
      // 实现用户登录
      if (!this.login.username) {
        this.$layer.msg("请输入邮箱账号");
        return;
      }

      if (this.login.password === '') {
        layer.msg("密码不能为空");
        return;
      }

      // console.log("登录请求:", this.login);
      API.login(this.login).then(res => {
          this.$layer.msg("登录成功！");
          Token.saveToken(res.access, res.refresh, this.login.rememberMe);
          router.push({ name: 'home' })
      });
    },

    onSubmitRegister() {
      const { email, password, password2, name } = this.form;

      // 邮箱校验
      if (!email) {
        this.$layer.msg("请输入邮箱账号");
        return;
      }
      // 简单的邮箱格式校验（可选）
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(email)) {
        this.$layer.msg("邮箱格式不正确");
        return;
      }

      // 密码校验
      if (!password) {
        this.$layer.msg("请输入密码");
        return;
      }
      if (password.length < 6) {
        this.$layer.msg("密码长度不能少于6位");
        return;
      }

      // 再次确认密码
      if (!password2) {
        this.$layer.msg("请再次输入密码");
        return;
      }
      if (password !== password2) {
        this.$layer.msg("两次密码输入不一致");
        return;
      }

      // 班级选择校验
      if (!this.form.clazz_id) {
        this.$layer.msg("请选择班级");
        return;
      }

      // 真实姓名校验
      if (!name) {
        this.$layer.msg("请输入真实姓名");
        return;
      }

      // 如果全部校验通过
      this.$layer.msg("注册中，请稍候...");

      const user = {
        username: this.form.email,
        email: this.form.email,
        password: this.form.password,
        name: this.form.name,
        clazz: this.form.clazz_id,
        is_active: true,
        is_delete: false,
        role: 3,
      };
      API.register(user).then(
        res => {
          console.log("注册响应:", res);
          if(res.username === user.username) {
            // 注册成功
            this.$layer.msg("注册成功！");
            // 跳转到登录页，并保存令牌
            router.push({ name: 'login' });
            // 清空表单
            this.form = {
              email: "",
              password: "",
              password2: "",
              name: "",
              clazz_id: null,
            }
          };
        }
      ).catch(err => {
        console.error("注册失败:", err);
        this.$layer.msg("注册失败: " + (err.response?.data?.message || err.message));
      });
    },

    findPass() {
      this.$router.push({name: 'find-pwd'})
    }
  },
  components: {
    SimpleNav,
  }
};
</script>

<style scoped>
.login-form {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  user-select: none;
  box-sizing: border-box;
  height: calc(100vh - 61px);
}

.login-container {
  width: 900px;
  height: 560px;
  background-color: #f0f0f0;
  display: flex;
  border-radius: 20px 0 0 20px;
}

.login-bg {
  position: relative;
  width: 300px;
  background: #333 url(../assets/task-login-bg.png) no-repeat center / 230%;
  border-radius: 20px 0 0 20px;
  box-shadow: 0 0 10px #000;
}

.login-core {
  flex: auto 1 1;
}

.login-tab {
  height: 120px;
  line-height: 120px;
  text-align: center;
  font-size: 18px;
}

.login-tab span {
  padding: 10px 30px;
  cursor: pointer;
  position: relative;
  margin: 0 5px;
}

.login-tab span::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
}

.login-tab span.active::after {
  height: 4px;
  width: 100%;
  background-color: #5FB878;
  transition: all .5s;
}

.login-panel {
  padding: 10px 40px;
}

.login-fda {
  float: right !important;
  font-size: 14px;
}

</style>